package com.grimdawnofflinebuilder.util.template.templateReader

import com.grimdawnofflinebuilder.util.template.templateReader.parser.TPLBaseVisitor
import com.grimdawnofflinebuilder.util.template.templateReader.parser.TPLParser

/*
 * Copyright (C) 2017 Fromentin Xavier
 *
 * This file is part of GDOB.
 *
 * GDOB is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * GDOB is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

class TPLVisitorImpl : TPLBaseVisitor<Group>() {

    companion object {
        private fun trimQuotes( text: String ) = text.removePrefix("\"").removeSuffix("\"")
    }

    override fun visitGroup(ctx: TPLParser.GroupContext?): Group {
        val group = Group()

        // Attributes
        ctx?.nameAttr()?.let { group.name = trimQuotes( it.value().text ) }
        ctx?.typeAttr()?.let { group.type = trimQuotes( it.value().text ) }

        // Variables
        val varVisitor = VariableVisitor()
        val variables = ctx?.variable()?.map { varVisitor.visitVariable( it ) }
        variables?.let { group.variables.addAll( it ) }

        // Sub-Groups
        val subGroupVisitor = TPLVisitorImpl()
        val subGroups = ctx?.group()?.map { subGroupVisitor.visitGroup( it ) }
        subGroups?.let { group.subGroups.addAll( it ) }

        return group
    }

    class VariableVisitor : TPLBaseVisitor<Variable>() {

        override fun visitVariable(ctx: TPLParser.VariableContext?): Variable {
            val variable = Variable()

            // Attributes
            ctx?.nameAttr()?.let { variable.name = trimQuotes( it.value().text ) }
            ctx?.classAttr()?.let { variable.clazz = trimQuotes( it.value().text ) }
            ctx?.typeAttr()?.let { variable.type = trimQuotes( it.value().text ) }
            ctx?.descAttr()?.let { variable.description = trimQuotes( it.value().text ) }
            ctx?.valueAttr()?.let { variable.value = trimQuotes( it.value().text ) }
            ctx?.defaultValue()?.let { variable.defaultValue = trimQuotes( it.value().text ) }

            return variable
        }

    }

}